package com.dyy.AI_System.service.impl;

import com.dyy.AI_System.domain.po.DocumentCategories;
import com.dyy.AI_System.mapper.DocumentCategoriesMapper;
import com.dyy.AI_System.service.IDocumentCategoriesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 文档分类表 服务实现类
 * </p>
 *
 * @author dyy
 * @since 2025-10-14
 */
@Service
public class DocumentCategoriesServiceImpl extends ServiceImpl<DocumentCategoriesMapper, DocumentCategories> implements IDocumentCategoriesService {

    @Override
    public IPage<DocumentCategories> pageQuery(Integer pageNum, Integer pageSize, String keyword) {
        Page<DocumentCategories> page = new Page<>(pageNum, pageSize);
        QueryWrapper<DocumentCategories> queryWrapper = new QueryWrapper<>();
        
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like("name", keyword)
                    .or().like("description", keyword);
        }
        
        queryWrapper.orderByAsc("sort_order");
        
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public boolean updateStatus(Long id, Boolean isActive) {
        if (id == null) {
            return false;
        }
        DocumentCategories category = new DocumentCategories();
        category.setId(id);
        category.setIsActive(isActive);
        category.setUpdatedAt(LocalDateTime.now());
        
        return updateById(category);
    }

    @Override
    public boolean batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return removeByIds(ids);
    }

    @Override
    public List<DocumentCategories> getCategoryTree() {
        // 查询所有分类
        List<DocumentCategories> allCategories = list();
        List<DocumentCategories> rootCategories = new ArrayList<>();
        
        for (DocumentCategories category : allCategories) {
            Long parentId = category.getParentId();
            if (parentId == null || parentId == 0) {
                // 根分类
                rootCategories.add(category);
            }
        }
        
        // 按排序字段排序
        rootCategories.sort(Comparator.comparingInt(DocumentCategories::getSortOrder));
        
        return rootCategories;
    }

}
